package com.zhc.excel.service.impl;

import java.util.Map;
import java.util.Map.Entry;

import org.springframework.stereotype.Service;

import com.zhc.common.file.strategy.StrategyContext;
import com.zhc.common.file.strategy.processor.AbstractImportFileTemplate;
import com.zhc.common.sdk.api.dto.file.ImportFileResultEnum;
import com.zhc.common.sdk.api.dto.file.ImportLogObject;
import com.zhc.common.utils.serialize.JsonHelper;
import com.zhc.excel.domain.ImportOperateInfo;

/**
 * 说明：
 * @author jinsicao
 * @version 2017年9月4日
 */
@Service("importExampleStrategy")
public class ImportExampleStrategyImpl extends AbstractImportFileTemplate<ImportOperateInfo> {

	@Override
	protected boolean preDataFromFileDataMap(StrategyContext strategyContext) {
		// 数据内容
		for (Entry<Integer, Map<Integer, Object>> entry : strategyContext.getFileDataMap().entrySet()) {
			
//			if (entry.getKey().equals(0)) {
//				// 跳过标题行
//				continue;
//			}
			try {
				ImportLogObject importObject = strategyContext.createImportLogObject(entry);
				try {
					if (importObject != null) {
						Map<Integer, Object> dataMap = entry.getValue();
						LOG.info(String.format("importExampleStrategy#preDataFromExcelDataMap line【%s】 dataMap【%s】", entry.getKey(), JsonHelper.toJson(entry.getValue())));
						importObject.setData(dataMap);
					}
				} catch (Exception e) {
					importObject.setStatusByResultEnum(ImportFileResultEnum.CONV_PARAM_ERROR, e.getMessage());
					LOG.error("importExampleStrategy#preDataFromExcelDataMap Exception :", e);
				}
			} catch (Exception e1) {
				LOG.error("importExampleStrategy#preDataFromExcelDataMap createImportObject Exception :", e1);
			}
		}
		return true;
	}

	@Override
	protected boolean executeImport(StrategyContext strategyContext) {
		int success = 0;
		for (ImportLogObject importObject : strategyContext.getExecuteDataList()) {
			boolean result = true;
			LOG.info(String.format("importExampleStrategy#executeImport line【%s】 dataMap【%s】", importObject.getExcelNo(), JsonHelper.toJson(importObject.getData())));
			if (result) {
				importObject.setStatusByResultEnum(ImportFileResultEnum.SUCCESS, null);
				success++;
			} else {
				importObject.setStatusByResultEnum(ImportFileResultEnum.BUSINESS_PARAM_ERROR, null);
			}
		}
		strategyContext.setSuccessCount(success);
		return true;
	}
}
